<template>
  <div class="notice-container">
    <!-- 左侧导航 -->
    <el-menu
        default-active="1"
        class="el-menu-vertical-demo"
        @select="handleMenuSelect"
        background-color="#1f2126"
        text-color="#bfc3c9"
        active-text-color="#409eff"
    >
      <el-menu-item index="1">
        <i class="el-icon-at"></i>
        <span>通知</span>
        <span v-if="noticeCounts.all > 0" class="badge">{{ noticeCounts.all }}</span>
      </el-menu-item>
      <el-menu-item index="2">
        <i class="el-icon-chat-dot-round"></i>
        <span>点赞</span>
        <span v-if="noticeCounts.like > 0" class="badge">{{ noticeCounts.like }}</span>
      </el-menu-item>
      <el-menu-item index="3">
        <i class="el-icon-star-on"></i>
        <span>评论</span>
        <span v-if="noticeCounts.comment > 0" class="badge">{{ noticeCounts.comment }}</span>
      </el-menu-item>
      <el-menu-item index="4">
        <i class="el-icon-message"></i>
        <span>收藏</span>
        <span v-if="noticeCounts.collection > 0" class="badge">{{ noticeCounts.collection }}</span>
      </el-menu-item>
      <el-menu-item index="5">
        <i class="el-icon-bell"></i>
        <span>关注</span>
        <span v-if="noticeCounts.follow > 0" class="badge">{{ noticeCounts.follow }}</span>
      </el-menu-item>
      <el-menu-item index="6">
        <i class="el-icon-bell"></i>
        <span>私信</span>
        <span v-if="noticeCounts.message > 0" class="badge">{{ noticeCounts.message }}</span>
      </el-menu-item>
    </el-menu>
    <!-- 右侧内容区域 -->
    <div class="content-wrapper">
      <div class="notice-card-list">
        <NoticeCard
            v-for="item in filteredNotices"
            :key="item.id"
            :notice="item"
            @delete="handleDelete"
            @viewDetail="openDetail"
        />
      </div>
      <!-- 抽屉组件 -->
      <NoticeDetailDrawer ref="detailDrawer" />
    </div>
  </div>
</template>

<script setup lang="ts">
// 1. 修正导入：从 vue-router 导入 onBeforeRouteLeave
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import NoticeCard from './NoticeCard.vue'
import NoticeDetailDrawer from './NoticeDetailDrawer.vue'
import { useUserStore } from '@/stores/user'
import { useNotificationStore } from '@/stores/notificationStore'
import { onBeforeRouteLeave } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()
const notificationStore = useNotificationStore()

const userId = ref(userStore.id)
const detailDrawer = ref(null)
const activeTab = ref('1')

// 从store获取通知数据和计数
const noticeCounts = computed(() => notificationStore.noticeCounts)

// 根据当前标签过滤的通知列表
const filteredNotices = computed(() => {
  const typeMap = {
    '1': 'all',
    '2': 'like',
    '3': 'comment',
    '4': 'collection',
    '5': 'follow',
    '6': 'message'
  }

  const targetType = typeMap[activeTab.value] || 'all'
  return notificationStore.getNoticesByType(targetType)
})

// 打开详情抽屉并标记通知为已读
const openDetail = async (notice) => {
  try {
    if (notice.type === 'comment') {
      const { data } = await axios.get(`/api/notice/comment/${notice.id}`)
      notice.commentText = data.commentText
    }

    if (detailDrawer.value) {
      detailDrawer.value.handleDetailData(notice)

      if (notice.isRead !== 1) {
        await notificationStore.markNoticeAsRead(notice.id)
        // 手动更新当前通知的 isRead，避免组件重新渲染后状态丢失
        notice.isRead = 1
      }
    }
  } catch (error) {
    ElMessage.error('获取通知详情失败，请稍后重试')
    console.error('获取通知详情失败:', error)
  }
}

// 删除通知
const handleDelete = async (id: string) => {
  try {
    await notificationStore.deleteNotice(id)
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error('删除失败，请稍后重试')
    console.error('删除通知失败:', error)
  }
}

// 切换左侧分类
const handleMenuSelect = (key: string) => {
  activeTab.value = key
}


// 添加路由离开守卫
onBeforeRouteLeave(async (to, from) => {
  try {
    if (userId.value && notificationStore.noticeCounts.all > 0) {
      await notificationStore.markAllNoticesAsRead(userId.value)
      console.log('离开通知页面，已标记所有通知为已读')
    }
  } catch (error) {
    console.error('离开时标记已读失败:', error)
  }
})


// 组件挂载时：优先使用全局状态中的数据，避免重复请求覆盖已读状态
onMounted(async () => {
  if (!userId.value) {
    ElMessage.warning('请先登录以查看通知')
    return
  }

  try {
    // 只有当全局状态中没有数据时，才重新请求（避免覆盖已更新的isRead）
    if (notificationStore.notices.length === 0) {
      await notificationStore.fetchNotices(userId.value)
    } else {
      console.log('使用全局状态中的通知数据（包含已更新的已读状态）')
    }
  } catch (error) {
    ElMessage.error('获取通知数据失败，请稍后重试')
  }
})
</script>


<style scoped>
.notice-container {
  display: flex;
  height: calc(100vh - 60px); /* 可根据实际布局调整高度 */
  background-color: #fff; /* 深色背景，适配示例界面 */
  color: #fff;
}

/* 左侧菜单样式 */
.el-menu-vertical-demo {
  border-right: none; /* 去掉默认边框 */
  background-color: #fff;
}

.el-menu-item {
  color: #bfc3c9;
}

.el-menu-item.is-active {
  color: #409eff;
}

/* 右侧内容区域 */
.content-wrapper {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

/* 暂无内容提示 */
.empty-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.empty-tip i {
  margin-right: 8px;
  font-size: 24px;
  color: #666;
}

/* 通知卡片列表 */
.notice-card-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
}
</style>